package com.im.web.controller;

import com.im.common.config.ImServerConfig;
import com.im.web.core.controller.BaseController;
import com.im.web.session.UserInfoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author gongym
 * @date 2019/1/26 18:55
 */
@Controller
@RequestMapping(value = "/api/im/avatar/", produces = "text/plain;charset=UTF-8")
public class AvatarController extends BaseController {
  private final ImServerConfig imServerConfig;
  private final UserInfoSession userInfoSession;

  @Autowired
  public AvatarController(ImServerConfig imServerConfig, UserInfoSession userInfoSession) {
    this.imServerConfig = imServerConfig;
    this.userInfoSession = userInfoSession;
  }

  @RequestMapping(value = "upload", method = RequestMethod.POST)
  public void updateAvatar(MultipartFile file) {
    Long currentUser = userInfoSession.getCurrentUser();
    String avatarPath = imServerConfig.getAvatarPath();
    File dest = new File(avatarPath + currentUser + ".jpg");
    if (!dest.getParentFile().exists()) {
      //noinspection ResultOfMethodCallIgnored
      dest.getParentFile().mkdir();
    }
    try {
      file.transferTo(dest);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public void downloadAvatar() {}
}
